package com.ays.comm;

import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * @author Administrator
 * @date 2024/6/7
 * @desc xml转换
 */
@Slf4j
public class XMLHandle {

    public static JSONObject getJson(String xml, String module){
        JSONObject entries = XML.toJSONObject(xml);
        JSONObject body = entries.get("Request", JSONObject.class).get("Body", JSONObject.class);
        return body;
    }

    public static JSONObject getJson(HttpServletRequest rq, String module) throws IOException {
        InputStream is = rq.getInputStream();
        byte[] b = new byte[1024*5];
        int i = is.read(b);
        while(i != -1) {
            i = is.read(b);
        }
        String result = new String(b).trim();
        JSONObject entries = XML.toJSONObject(result);
        JSONObject body = entries.get("Request", JSONObject.class).get("Body", JSONObject.class);
        return body;
    }

    public static String getXml(String data){
        JSONObject result = new JSONObject();
        JSONObject header = new JSONObject();
        header.putOnce("SourceSystem","anes");
        header.putOnce("MessageID",new Date().getTime());
        result.putOnce("Response",header);
        JSONObject body = new JSONObject();
        if("ok".equals(data)){
            body.putOnce("ResultCode","0");
            body.putOnce("ResultContent","成功");
            JSONObject successIDList = new JSONObject();
            successIDList.putOnce("RowID",data);
            body.putOnce("SuccessIDList",successIDList);
        }else {
            body.putOnce("ResultCode","-1");
            body.putOnce("ResultContent","失败：" + data);
        }
        result.putOnce("Body",body);
        String xml = XML.toXml(result);
        log.info("retun:{}",xml);
        return xml;
    }

}
